#pragma once

#include <iostream>
#include <sys/select.h>
#include <sys/time.h>
#include "Socket.hpp"
using namespace std;

static const uint16_t defaultport=8500;

class SelectServer
{
public:
    SelectServer(uint16_t port=defaultport):_port(port)
    {}

    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();

        return true;
    }

    void Start()
    {
        int listensock=_listensock.Fd();
        for(;;)
        {
            //不能直接accept，检测并且获取listensock上面的事件，新连接到来，等价于读事件就绪
            fd_set rfds;
            FD_ZERO(&rfds); //清空文件描述符
            FD_SET(listensock,&rfds); //添加指定描述符
            
            struct timeval timeout={5,0};

            int n=select(listensock+1,&rfds,nullptr,nullptr,/*&timeout*/nullptr);
            switch(n)
            {
                case 0:
                    cout<<"time out"<<endl;
                    break;
                case -1:
                    cerr<<"select error"<<endl;
                    break;
                default:
                    //cout<<"有事件就绪"<<endl;
                    break;
            }
        }
    }

    ~SelectServer()
    {
        _listensock.Close();
    }

private:
    Sock _listensock;
    uint16_t _port;
};